
import { isPlainObject, isString } from 'lodash';

function isFSA(action) {
  return (
    isPlainObject(action) &&
    isString(action.type) &&
    Object.keys(action).every(key => ['type', 'payload', 'error', 'meta'].indexOf(key) > -1)
  );
}

export default (store) => (next) => (action) => {
  const { dispatch } = store;
  if (action instanceof Promise) {
    return action.then(dispatch)
  } else if (isFSA(action) && action.payload instanceof Promise) {
    return action.payload
      .then(result => dispatch({ ...action, payload: result }))
      .catch(error => dispatch({ ...action, payload: error, error: true }))
  } else if (typeof action === 'function') {
    return action(store);
  } else {
    return next(action);
  }
}